package com.btkjgc.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.CarAccount;
import com.btkjgc.models.CartypePostage;
import com.btkjgc.models.CouponReceive;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.extend.AccountUserModel;
import com.btkjgc.models.extend.CarAccountModel;
import com.btkjgc.models.extend.CarModel;
import com.btkjgc.models.extend.CartypePostageModel;
import com.btkjgc.models.extend.CouponReceiveModel;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.service.intf.AccountUserManageService_Intf;

@Controller
public class AccountUserManageController
{
	static Logger logger = Logger.getLogger(AccountUserManageController.class);
	
	@Autowired
	private AccountUserManageService_Intf accountuserManageService;
	
	@RequestMapping(value = "account_user_manage", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView getBusinessRecords(HttpServletRequest request) 
	{
		ModelAndView mv = new ModelAndView("account_user_manage");
		listrecord(request,mv);
		return mv;
	}
	
	@RequestMapping(value = "edit_private_account_user", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String editPrivateAccountUser(AccountUserModel accountUserModel)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException{
		
		System.out.println("EditPrivateAccountUser");
		accountuserManageService.updatePrivateAccountUser(accountUserModel);
		
		return "redirect:/account_user_manage";
	}
	
	@RequestMapping(value = "edit_company_account_user")
	@ResponseBody
	public AjaxObj editCompanyAccountUser(AccountUserModel accountUserModel)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException{
		
		AjaxObj ajaxObj=accountuserManageService.updateCompanyAccountUser(accountUserModel);
		
		return ajaxObj;
	}
	
	@RequestMapping(value = "batchdel_account_user", method = {
			RequestMethod.GET, RequestMethod.POST })
	public String batchdelAccountUser(HttpServletRequest request, String idStr) {
		String[] ids = idStr.split(",");
		for (int i = 0; i < ids.length; i++) {
			int accountUserId = Integer.valueOf(ids[i]);
			//个人对公账号车辆解绑，公司账号所有旗下车辆解绑
			String sql = "select aut.* from account_user_t aut where aut.id="+accountUserId;
			AccountUserModel accountUserModel = (AccountUserModel)HibernateUtil.executeSQLQueryObject(sql, AccountUserModel.class);
			if(accountUserModel.getType()==0){//个人账号
				String carsql = "select cat.* from car_account_t cat where cat.accountid="+accountUserId;
				CarAccount carAccount = (CarAccount)HibernateUtil.executeSQLQueryObject(carsql, CarAccount.class);
				if(carAccount!=null&&carAccount.getSelf()==0){//对公个人账号
					String hql = "update from CarAccount set del=1 where accountid="+accountUserId;
					HibernateUtil.executeUpdate(hql);
				}
			}
			accountuserManageService.deleteById(accountUserId);
		}
		return "redirect:/account_user_manage";
	}
	
	@RequestMapping(value = "batch_add_coupon", method = RequestMethod.GET)
	public @ResponseBody
	Integer jsonAddCoupon(HttpServletRequest request, String idStr, CouponReceiveModel couponReceiveModel) {
		String[] ids = idStr.split(",");
		ArrayList<CouponReceive> coupons= new ArrayList<>();
		for (int i = 1; i <= ids.length; i++) {
			CouponReceive couponReceive = new CouponReceive();
			int accountUserId = Integer.valueOf(ids[i-1]);
			couponReceive.setAccountid(accountUserId);
			couponReceive.setCouponid(couponReceiveModel.getCouponid());
			couponReceive.setCreatedate(new Date());
			couponReceive.setDel(0);
			couponReceive.setUsed(1);
			coupons.add(couponReceive);
		}
		accountuserManageService.insertCoupon(coupons);
		return 1;
	}
	
	@RequestMapping(value = "match_postage", method = {RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	Integer jsonMatchPostage(HttpServletRequest request, CartypePostageModel cartypePostageModel) {
		if(cartypePostageModel.getAction()==1){//update
			CartypePostage cartypePostage = new CartypePostage();
			if(cartypePostageModel.getPostage_type()==1){//常规资费
				cartypePostage.setAccountid(cartypePostageModel.getAccountid());
				cartypePostage.setCartype(cartypePostageModel.getCartype());
				cartypePostage.setPostage_type(1);
				cartypePostage.setPostage_id(cartypePostageModel.getCpostageId());
			}else{//套餐资费
				cartypePostage.setAccountid(cartypePostageModel.getAccountid());
				cartypePostage.setCartype(cartypePostageModel.getCartype());
				cartypePostage.setPostage_type(2);
				cartypePostage.setPostage_id(cartypePostageModel.getPpostageId());
			}
			accountuserManageService.updatePostage(cartypePostage);
		}else{//insert
			CartypePostage cartypePostage = new CartypePostage();
			if(cartypePostageModel.getPostage_type()==1){//常规资费
				cartypePostage.setAccountid(cartypePostageModel.getAccountid());
				cartypePostage.setCartype(cartypePostageModel.getCartype());
				cartypePostage.setPostage_type(1);
				cartypePostage.setPostage_id(cartypePostageModel.getCpostageId());
			}else{//套餐资费
				cartypePostage.setAccountid(cartypePostageModel.getAccountid());
				cartypePostage.setCartype(cartypePostageModel.getCartype());
				cartypePostage.setPostage_type(2);
				cartypePostage.setPostage_id(cartypePostageModel.getPpostageId());
			}
			accountuserManageService.insertPostage(cartypePostage);
		}
		return 1;
	}
	
	@SuppressWarnings("unchecked")
	public void listrecord(HttpServletRequest request, ModelAndView mv)
	{	
		String tel = request.getParameter("tel");
		String carbrand = request.getParameter("carbrand");
		String type = request.getParameter("Acctype");
		String account = request.getParameter("account");
		String cartype = request.getParameter("cartype");
		String cityid = request.getParameter("cityid");
		String carstatus = request.getParameter("carstatus");
		String page = request.getParameter("page");
		String sortfield = request.getParameter("sortfield");
		if (StringUtils.isEmpty(sortfield)) {
			sortfield = "createdate";
		}
		
		int pageIndex = 0;
		int totalRecord = 0;
		if (page != null)
		{
			pageIndex = Integer.parseInt(page);
		}
		
		List<Object[]> paramList = new ArrayList<Object[]>();
		Object[] arr1={"tel","like",tel};
		Object[] arr2={"carbrand","like",carbrand};
		Object[] arr3={"company","=",account};
		Object[] arr4={"cartypeid","=",cartype};
		Object[] arr5={"type","=",type};
		Object[] arr6={"cityid","=",cityid};
		Object[] arr7={"catdel","=",carstatus};
		paramList.add(arr1);
		paramList.add(arr2);
		paramList.add(arr3);
		paramList.add(arr4);
		paramList.add(arr5);
		paramList.add(arr6);
		paramList.add(arr7);
		
		String sql =
				"SELECT * FROM(SELECT\n" +
						" cat.carbrand,\n" +
						" aut.*, cpt.postage_type,\n" +
						" conpt.id AS conid,\n" +
						" conpt.`name` AS conventional,\n" +
						" conpt.operdate AS condate,\n" +
						" ppt.id AS packid,\n" +
						" ppt.`name` AS pack,\n" +
						" ppt.operdate AS packdate,\n" +
						" adm.username AS operator,\n" +
						" ct.`Name` AS city,\n" +
						" cat.cartypeid,\n" +
						" cat.del AS catdel,\n" +
						" (SELECT name from cartype_t WHERE id=cpt.cartype)cartypename,\n" +
						" CASE cat.del\n" +
						" WHEN 0 THEN\n" +
						" '已绑定'\n" +
						" WHEN 1 THEN\n" +
						" '未绑定'\n" +
						" WHEN 2 THEN\n" +
						" '解绑中'\n" +
						" END carstatus\n" +
						"FROM\n" +
						" account_user_t aut\n" +
						"LEFT JOIN car_account_t cat ON cat.accountid = aut.id\n" +
						"LEFT JOIN cartype_postage_t cpt ON cpt.accountid = aut.id\n" +
						"LEFT JOIN admin_user_t adm ON adm.id = aut.operatorid\n" +
						"LEFT JOIN cities_t ct ON ct.id = aut.cityid\n" +
						"LEFT JOIN conventional_postage_t conpt ON cpt.postage_id = conpt.id\n" +
						" AND cpt.postage_type = 1\n" +
						"LEFT JOIN package_postage_t ppt ON cpt.postage_id = ppt.id\n" +
						" AND cpt.postage_type = 2\n" +
						"GROUP BY id)a\n" +
						"WHERE a.del = 0";
		
		sql = accountuserManageService.getwhereSQL(sql, paramList, sortfield);
		
		//获取分页查询的数据结果
		totalRecord = accountuserManageService.getCount(sql, paramList);
				
		List<AccountUserModel> accountUserModel = accountuserManageService.getList(
				AccountUserModel.class, paramList, sql, pageIndex, 15, sortfield);
		
		//设置后台用户界面所需的其他数据
		accountuserManageService.setListData(request,mv,pageIndex,totalRecord,accountUserModel);
		
	}
	
	@RequestMapping(value = "get_self_by_id")
	@ResponseBody
	public CarAccount getSelfById(Integer id) {
		
		String sql = "select * from car_account_t where accountid = ?";
		
		CarAccount carAccount = (CarAccount)HibernateUtil.executeSQLQueryObject(sql, CarAccount.class, id);
		
		return carAccount;
	}
	
	@RequestMapping(value = "get_postage_by_cartype")
	@ResponseBody
	public Integer getPostageByCartype(CartypePostage cartypePostage) {
		
		String sql = "SELECT count(*)\n"
				   + " FROM\n"
				   + " cartype_postage_t\n"
				   + " WHERE cartype=" + cartypePostage.getCartype()
				   + " AND accountid=" + cartypePostage.getAccountid();
		
		Integer flag=HibernateUtil.executeSQLQueryInt(sql);
		
		return flag;
	}
	
	@RequestMapping(value = "get_accountuser_by_id")
	@ResponseBody
	public AccountUserModel getAccountuserById(Integer id) {
		
		String sql = "SELECT\n"
				   + " aut.*,cat.cartypeid,cat.carbrand,cat.carid,\n"
				   + " ct.free,ct.firstfee,ct.lastfee\n"
				   + "FROM\n"
				   + " account_user_t aut\n"
				   + " LEFT JOIN car_account_t cat ON cat.accountid=aut.id\n"
				   + " LEFT JOIN car_t ct ON ct.id = cat.carid\n"
				   + "WHERE aut.id = ?";
		
		AccountUserModel accountUserModel = (AccountUserModel) HibernateUtil
				.executeSQLQueryObject(sql,AccountUserModel.class,id);
		
		return accountUserModel;
	}
	
	@RequestMapping(value = "get_cartypelist_by_id")
	@ResponseBody
	public List<Dictionary> getCartypeListById(AccountUserModel accountUserModel) {
		
		List<Dictionary> cartype=null;
		
		if(accountUserModel.getType()==0){//个人
			String sql1=" select ct.name,CONCAT(ct.id,'') 'key' from cartype_t ct LEFT JOIN car_account_t cat ON cat.cartypeid=ct.id where cat.accountid="+accountUserModel.getId();
			cartype = HibernateUtil.executeSQLQueryList(sql1, Dictionary.class);
			if(cartype.size()!=0){
				cartype.get(0).setSql("private");//返回个人
			}
		}else{//公司
			String sql2=" select ct.name,CONCAT(car.cartypeid,'') 'key' from car_t car LEFT JOIN cartype_t ct ON ct.id=car.cartypeid\n"+
					"LEFT JOIN account_user_t aut ON aut.id=car.companyid where aut.id="+accountUserModel.getId()+" GROUP BY car.cartypeid";
			cartype = HibernateUtil.executeSQLQueryList(sql2, Dictionary.class);
		}
		
		return cartype;
	}
	
	@RequestMapping(value = "get_cartype")
	@ResponseBody
	public List<Dictionary> getCartypeById(CarModel carModel) {
		
		List<Dictionary> cartype=null;
		
		String sql = " SELECT ctt.name,ct.cartypeid id FROM cartype_t ctt LEFT JOIN car_t ct ON ct.cartypeid = ctt.id WHERE ct.companyid ="+carModel.getCompanyid()+" GROUP BY ct.cartypeid";
		cartype = HibernateUtil.executeSQLQueryList(sql, Dictionary.class);
		
		return cartype;
	}
	
	@RequestMapping(value = "get_postage_by_id")
	@ResponseBody
	public List<Dictionary> getPostageById(CartypePostageModel cartypePostageModel) {
		
		List<Dictionary> postage=null;
		
		String sql = " SELECT cpt.postage_type as type,conpt.name,ppt.name as value\n"
				+ " from\n"
				+ " cartype_postage_t cpt\n"
				+ " LEFT JOIN conventional_postage_t conpt ON cpt.postage_id = conpt.id\n"
				+ "	AND cpt.postage_type = 1\n"
				+ " LEFT JOIN package_postage_t ppt ON cpt.postage_id = ppt.id\n"
				+ "	AND cpt.postage_type = 2\n"
				+ " WHERE cpt.accountid="+cartypePostageModel.getAccountid()+" AND cpt.cartype="+cartypePostageModel.getCartype();
		postage = HibernateUtil.executeSQLQueryList(sql, Dictionary.class);
		
		return postage;
	}
	
	@RequestMapping(value = "get_cartypeid")
	@ResponseBody
	public Integer getCartypeid(CarModel carModel) {
		
		String sql = " select cartypeid from car_t where id="+carModel.getId();
		Integer cartypeid = HibernateUtil.executeSQLQueryInt(sql);
		
		return cartypeid;
	}
	
	@RequestMapping(value = "add_account_user/{a}", method = RequestMethod.GET)
	public @ResponseBody
	Integer jsonAddAccountUser(HttpServletRequest request,
			@PathVariable("a") int a, AccountUserModel accountUserModel){
		
		//判断用户类型
		if(accountUserModel.getType()==0){//个人
			AccountUserModel privateModel = new AccountUserModel();
			privateModel.setType(0);
			privateModel.setName(accountUserModel.getName());
			privateModel.setTel(accountUserModel.getTel());
			privateModel.setIdentityid(accountUserModel.getIdentityid());
			privateModel.setProvinceid(accountUserModel.getProvinceid());
			privateModel.setCityid(accountUserModel.getCityid());
			privateModel.setDel(0);
			privateModel.setCreatedate(new Date());
			privateModel.setLoginnum(0);
			
			Integer reInt = accountuserManageService
					.insertAccountUser(privateModel);
			return reInt;
		}else{//企业
			AccountUserModel companyModel = new AccountUserModel();
			companyModel.setType(1);
			companyModel.setName(accountUserModel.getCname());
			companyModel.setTel(accountUserModel.getCtel());
			companyModel.setBank_num(accountUserModel.getBank_num());
			companyModel.setBank_account(accountUserModel.getBank_account());
			companyModel.setComment(accountUserModel.getComment());
			companyModel.setDel(0);
			companyModel.setCreatedate(new Date());
			companyModel.setLoginnum(0);
			companyModel.setCompany(accountUserModel.getCname());
			Integer reInt = accountuserManageService
					.insertAccountUser(companyModel);
			return reInt;
		}
	}
	
	@RequestMapping(value = "bind_car", method = {RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	AjaxObj bindCar(HttpServletRequest request,
			CarAccountModel carAccountModel) {
		
		AjaxObj ajaxObj = accountuserManageService.bindCar(carAccountModel);
		
		return ajaxObj;
	}
	
	@RequestMapping(value = "unbind_car", method = {RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	AjaxObj unbindCar(HttpServletRequest request,
			CarAccountModel carAccountModel) {
		
		AjaxObj ajaxObj = accountuserManageService.unbindCar(carAccountModel);
		
		return ajaxObj;
	}
	
	@RequestMapping(value = "immediate_unbind_car", method = {RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody
	AjaxObj immediateUnbindCar(HttpServletRequest request,
			CarAccountModel carAccountModel) {
		
		AjaxObj ajaxObj = accountuserManageService.immediateUnbindCar(carAccountModel);
		
		return ajaxObj;
	}
}